<script setup>
import { ref, watch, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Warning } from '@element-plus/icons-vue'
import { getOrderDetail, payOrder, checkOrderPay } from '@/api/order'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  orderId: {
    type: String,
    default: '',
  },
})

const emit = defineEmits(['update:visible', 'payment-success'])

const loading = ref(false)
const orderInfo = ref(null)
// 支付方式
const paymentMethod = ref('lianlpay_offline')

// 支付状态轮询定时器
let paymentCheckTimer = null

// 是否已开始支付
const isPaymentStarted = ref(false)

// 监听弹窗显示状态，当显示时获取订单信息
watch(
  () => props.visible,
  newVal => {
    if (newVal && props.orderId) {
      fetchOrderInfo()
    } else {
      // 关闭弹窗时重置数据
      orderInfo.value = null
    }
  },
)

// 获取订单信息
const fetchOrderInfo = async () => {
  if (!props.orderId) {
    ElMessage.error('订单ID不能为空')
    closeDialog()
    return
  }

  loading.value = true
  try {
    const res = await getOrderDetail({ order_id: props.orderId })
    orderInfo.value = res.detail
    if (orderInfo.value.order_status !== '待支付') {
      ElMessage.warning('该订单不是待付款状态，无法进行支付')
      setTimeout(() => {
        closeDialog()
      }, 2000)
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
    closeDialog()
  } finally {
    loading.value = false
  }
}

// 检查支付状态
const checkPaymentStatus = async pay_no => {
  try {
    const res = await checkOrderPay(pay_no)
    if (res.status === 'success') {
      // 支付成功
      ElMessage.success('支付成功')
      emit('payment-success')
      closeDialog()
      // 清除定时器
      if (paymentCheckTimer) {
        clearInterval(paymentCheckTimer)
        paymentCheckTimer = null
      }
    }
  } catch (error) {
    console.error('检查支付状态失败:', error)
  }
}

// 处理支付
const handlePayment = async () => {
  if (!orderInfo.value || !orderInfo.value.order_bn) {
    ElMessage.error('订单信息不完整，无法完成支付')
    return
  }

  loading.value = true
  try {
    const res = await payOrder(orderInfo.value.order_bn, paymentMethod.value)
    if (res.gateway_url) {
      // 打开新窗口进行支付
      window.open(res.gateway_url, '_blank')
      ElMessage.success('正在跳转到支付页面...')
      isPaymentStarted.value = true

      // 开始轮询检查支付状态
      if (paymentCheckTimer) {
        clearInterval(paymentCheckTimer)
      }
      paymentCheckTimer = setInterval(() => checkPaymentStatus(res.accp_txno), 10000) // 每10秒检查一次
    } else {
      ElMessage.error('获取支付链接失败')
    }
  } catch (error) {
    console.error('支付失败:', error)
    ElMessage.error('支付失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 处理支付成功
const handlePaymentSuccess = () => {
  if (orderInfo.value?.order_bn) {
    checkPaymentStatus(orderInfo.value.order_bn)
  }
}

// 处理支付失败
const handlePaymentFailed = () => {
  ElMessage.warning('如果支付遇到问题，请联系客服处理')
  closeDialog()
}

// 组件卸载时清除定时器
onUnmounted(() => {
  if (paymentCheckTimer) {
    clearInterval(paymentCheckTimer)
    paymentCheckTimer = null
  }
})

// 关闭弹窗
const closeDialog = () => {
  if (paymentCheckTimer) {
    clearInterval(paymentCheckTimer)
    paymentCheckTimer = null
  }
  isPaymentStarted.value = false
  emit('update:visible', false)
}
</script>

<template>
  <el-dialog
    :title="isPaymentStarted ? '支付状态确认' : '订单支付'"
    v-model="props.visible"
    :close-on-click-modal="false"
    width="650px"
    @close="closeDialog"
  >
    <div v-loading="loading">
      <div v-if="orderInfo" class="payment-content">
        <template v-if="!isPaymentStarted">
          <div class="order-info">
            <div class="info-item">
              <span class="label">订单编号：</span>
              <span class="value">{{ orderInfo.order_bn }}</span>
            </div>
            <div class="info-item">
              <span class="label">订单金额：</span>
              <span class="value price">¥{{ orderInfo.amount }}</span>
            </div>
            <div class="info-item">
              <span class="label">下单时间：</span>
              <span class="value">{{ orderInfo.created_at }}</span>
            </div>
            <div class="info-item">
              <span class="label">收 货 人：</span>
              <span class="value">{{ orderInfo.address.consignee }} {{ orderInfo.address.mobile }}</span>
            </div>
            <div class="info-item">
              <span class="label">详细地址：</span>
              <span class="value">{{ orderInfo.member_address }}</span>
            </div>
          </div>

          <div class="payment-methods">
            <h3>选择支付方式</h3>
            <div class="methods-list">
              <el-radio-group v-model="paymentMethod">
                <el-radio label="lianlpay_offline">连连支付-线下转账</el-radio>
              </el-radio-group>
            </div>
          </div>
        </template>

        <template v-else>
          <div class="payment-status">
            <div class="status-info">
              <el-icon class="status-icon"><Warning /></el-icon>
              <p class="status-text">请确认您的支付状态</p>
              <p class="status-tip">如果您已完成支付，请点击"我已支付"按钮；如果支付遇到问题，请点击"支付未成功"按钮</p>
            </div>
          </div>
        </template>
      </div>

      <div v-else-if="!loading" class="empty-state">
        <el-empty description="未找到订单信息" />
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <template v-if="!isPaymentStarted">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="handlePayment" :disabled="!orderInfo">确认支付</el-button>
        </template>
        <template v-else>
          <el-button @click="handlePaymentFailed">支付未成功</el-button>
          <el-button type="primary" @click="handlePaymentSuccess">我已支付</el-button>
        </template>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.payment-content {
  padding: 10px;
}

.order-info,
.shipping-address {
  padding: 20px;
  margin-bottom: 30px;
  background-color: #f8f8f8;
  border-radius: 4px;

  .info-item {
    display: flex;
    margin-bottom: 15px;

    &:last-child {
      margin-bottom: 0;
    }

    .label {
      width: 5em;
      margin-right: 1em;
      color: #606266;
      text-align: justify;

      &::after {
        display: inline-block;
        width: 100%;
        content: '';
      }
    }

    .value {
      flex: 1;
      color: #303133;

      &.price {
        font-weight: bold;
        color: #f56c6c;
      }
    }
  }
}

.shipping-address {
  h3 {
    margin-bottom: 15px;
    font-size: 18px;
    color: #303133;
  }
}

.payment-methods {
  margin-bottom: 20px;

  h3 {
    margin-bottom: 15px;
    font-size: 18px;
    color: #303133;
  }

  .methods-list {
    padding: 15px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
  }
}

.empty-state {
  display: flex;
  justify-content: center;
  padding: 30px 0;
}

.payment-status {
  padding: 20px;
  text-align: center;

  .status-info {
    .status-icon {
      margin-bottom: 20px;
      font-size: 48px;
      color: #e6a23c;
    }

    .status-text {
      margin-bottom: 10px;
      font-size: 18px;
      color: #303133;
    }

    .status-tip {
      font-size: 14px;
      line-height: 1.5;
      color: #606266;
    }
  }
}
</style>
